package com.zhang.second.day06;

import com.zhang.second.utils.ItemViewCountPerWindow;
import com.zhang.second.utils.UserBehavior;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @title: 实时热门商品统计，每隔五分钟统计过去一小时商品TopN
 * @author: zhang
 * @date: 2022/2/2 10:21
 */
public class Example6 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<UserBehavior> dataStream = env
                .readTextFile("/Users/apple/IdeaProjects/flink_1.13/src/main/resources/UserBehavior.csv")
                .map(new MapFunction<String, UserBehavior>() {
                    @Override
                    public UserBehavior map(String value) throws Exception {
                        String[] fields = value.split(",");
                        return new UserBehavior(
                                fields[0], fields[1], fields[2], fields[3],
                                Long.parseLong(fields[4]) * 1000L //转化为毫秒
                        );
                    }
                })
                //过滤pv数据
                .filter(r -> r.type.equals("pv"))
                //分配时间戳和水位线
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<UserBehavior>forMonotonousTimestamps()
                                .withTimestampAssigner(new SerializableTimestampAssigner<UserBehavior>() {
                                    @Override
                                    public long extractTimestamp(UserBehavior element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                );
        //计算每个pv在每个窗口出现的次数
        SingleOutputStreamOperator<ItemViewCountPerWindow> itemViewCountPerWindow = dataStream
                .keyBy(r -> r.itemId)
                .window(SlidingEventTimeWindows.of(Time.hours(1), Time.minutes(5)))
                .aggregate(new CountAgg(), new WindowResult());

        //计算每个窗口中商品count倒序输出
        itemViewCountPerWindow
                .keyBy(r -> r.windowEndTime)
                .process(new HotTopN(3))
                .print();
        env.execute();
    }

    public static class HotTopN extends KeyedProcessFunction<Long, ItemViewCountPerWindow, String> {
        private Integer n;

        public HotTopN(Integer n) {
            this.n = n;
        }

        private ListState<ItemViewCountPerWindow> listState;

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(
                    new ListStateDescriptor<ItemViewCountPerWindow>("list-state", Types.POJO(ItemViewCountPerWindow.class))
            );
        }

        @Override
        public void processElement(ItemViewCountPerWindow value, KeyedProcessFunction<Long, ItemViewCountPerWindow, String>.Context ctx, Collector<String> out) throws Exception {
            listState.add(value);

            ctx.timerService().registerEventTimeTimer(value.windowEndTime + 1L);
        }

        @Override
        public void onTimer(long timestamp, KeyedProcessFunction<Long, ItemViewCountPerWindow, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
            List<ItemViewCountPerWindow> arrayList = new ArrayList<>();
            for (ItemViewCountPerWindow e : listState.get()) arrayList.add(e);
            //清理状态减小内存压力
            listState.clear();
            //排序
            arrayList.sort(new Comparator<ItemViewCountPerWindow>() {
                @Override
                public int compare(ItemViewCountPerWindow o1, ItemViewCountPerWindow o2) {
                    return o2.count.intValue() - o1.count.intValue();
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("=================" + new Timestamp(ctx.timerService().currentWatermark()) + "==================\n");
            result.append("窗口结束时间：" + new Timestamp(timestamp - 1L)+"\n");
            for (int i = 0; i < n; i++) {
                ItemViewCountPerWindow tmp = arrayList.get(i);
                result.append("NO."+(i+1)+"商品ID："+tmp.itemId+",被浏览次数："+tmp.count+"\n");
            }
            result.append("========================================\n");

            out.collect(result.toString());
        }
    }


    public static class CountAgg implements AggregateFunction<UserBehavior, Long, Long> {
        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(UserBehavior value, Long accumulator) {
            return accumulator + 1L;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return null;
        }
    }

    public static class WindowResult extends ProcessWindowFunction<Long, ItemViewCountPerWindow, String, TimeWindow> {
        @Override
        public void process(String key, ProcessWindowFunction<Long, ItemViewCountPerWindow, String, TimeWindow>.Context context, Iterable<Long> elements, Collector<ItemViewCountPerWindow> out) throws Exception {
            out.collect(new ItemViewCountPerWindow(
                    key,
                    elements.iterator().next(),
                    context.window().getStart(),
                    context.window().getEnd()
            ));
        }
    }
}
